<?php

namespace addons\exam\model;


use addons\exam\enum\CommonStatus;
use addons\exam\enum\UserScoreType;
use addons\exam\library\ScoreService;
use app\admin\model\exam\QuestionCollectModel;
use app\common\services\UrlService;
use app\common\model\YalimediaQuestionLogDetail as DetailModel;

class QuestionModel extends \app\admin\model\exam\QuestionModel
{
    // 字段类型
    protected $type
        = [
            'options_img' => 'array',
            'options_extend' => 'array',
            'options_json' => 'array'
        ];

    // 隐藏字段
    // protected $hidden = [
    //     'answer', 'explain'
    // ];

    public function getKindList()
    {
        return [
            'JUDGE'    => '判断题',
            'SINGLE'   => '单选题',
            'MULTI'    => '多选题',
            'FILL'     => '填空题',
            'SHORT'    => '简答题',
            'MATERIAL' => '材料题',
            'WORD'     => '词汇题',
            'CALL'     => '通话题',
        ];
    }

    public function getDifficultyList()
    {
        return ['EASY' => '简单', 'GENERAL' => '普通', 'HARD' => '困难'];
    }

    public function getStatusList()
    {
        return ['NORMAL' => '正常', 'HIDDEN' => '隐藏'];
    }





    public function getOptionsJsonAttr($value)
    {
        if ($value = json_decode($value, true)) {
            $data = [];
            foreach ($value as $key => $row) {
                $arr['key']         = $key;
                $arr['value']       = $row;
                $arr['click_index'] = false;
                $arr['right_index'] = false;
                array_push($data, $arr);
            }
            return $data;
        }
        return [];
    }

    
    public function getAnswerAttr($value, $data)
    {
        if (is_array($value)) {
            return $value;
        }
        
        if (in_array($data['kind'], ['FILL', 'SHORT','CALL'])) {
            return json_decode($value, true);
        }
        return $value;
    }


    /***
     * 题目音频
     */
    public function getTitleImgAttr($value)
    {
        if(empty($value)){
            return '';
        }
        $value = $value ?? '';
        return cdnurl($value, true);
    }


    /***
     * 题目音频
     */
    public function getTitleAudioAttr($value)
    {
        if(empty($value)){
            return '';
        }
        $value = $value ?? '';
        return cdnurl($value, true);
    }

    public function getTitleVideoAttr($value, $data)
    {   
        if(empty($data['title_video'])){
            return '';
        }
        $value = $data['title_video'] ?? '';
        return cdnurl($value, true);
    }

    public function getTitleVideoUrlAttr($value, $data)
    {   
        if(empty($data['title_video'])){
            return '';
        }
        $value = $data['title_video'] ?? '';
        return cdnurl($value, true);
    }

    /**
     * 例句音频
     *
     * @param [type] $value
     * @return void
     */
    public function getExampleAudioAttr($value)
    {

        if(empty($value)){
            return '';
        }
        $value = $value ?? '';
        return cdnurl($value, true);
    }


    /**
     * 解析音频
     *
     * @param [type] $value
     * @return void
     */
    public function getExplainAudioAttr($value)
    {
        if(empty($value)){
            return '';
        }
        $value = $value ?? '';
        return cdnurl($value, true);
    }

    

    // public function getOptionsExtendAttr($value)
    // {
    //     return json_decode($value, true);
    // }

    /**
     * 试题是否已收藏过
     * @param $user_id
     * @param $questions
     * @return mixed
     */
    public static function isCollected($user_id, $questions)
    {
        $ids         = array_column($questions, 'id');
        $collects    = QuestionCollectModel::where('user_id', $user_id)->whereIn('question_id', $ids)->select();
        $collect_ids = array_column(collection($collects)->toArray(), 'question_id');

        foreach ($questions as &$question) {
            $question['collected'] = in_array($question['id'], $collect_ids);
        }

        return $questions;
    }

    /**
     * 获取试题列表
     * @param $params
     * @return array|int
     */
    public static function getList($params)
    {
        $param = array_merge([
            'cate_id'        => 0,                            // 按分类查询
            'kind'           => '',                           // 试题类型查询
            'status'         => CommonStatus::NORMAL,         // 状态查询
            'keyword'        => '',                           // 搜索关键词
            'user_id'        => 0,                            // 传入用户ID时，查询收藏状态
            'page_count'     => 20,                           // 每页数量
            'sort'           => '',                           // 排序类型
            'just_get_count' => 0,                            // 仅获取题数
            'mode'           => 'normal',                     // normal=普通模式，memory=记忆模式，random=随机查询
            'memory_index'   => 0,                            // 记忆模式 - 上次做题题标
        ], $params);

        $model = new static();
        $model->with(['materialQuestions.question'])->where('is_material_child', 0);

        // 查询条件
        if ($param['cate_id']) {
            $model->where('cate_id', $param['cate_id']);
        }
        if ($param['kind']) {
            $model->where('kind', $param['kind']);
        }
        if ($param['status']) {
            $model->where('status', $param['status']);
        }
        if ($param['keyword']) {
            $model->where('title', 'like', '%' . $param['keyword'] . '%');
        }

        // 仅获取题数
        if ($param['just_get_count']) {
            return ['total' => $model->count()];
        }

        // 排序
        if ($param['sort']) {
            $model->order($param['sort']);
        }
      
        // 能否获得积分标识
        $can_get_score = false;
        switch ($param['mode']) {
            // 记忆模式
            case 'memory':
                $list['data']  = $model->select();
                $can_get_score = true;
                break;

            // 随机模式
            case 'random':
                // 限制最多500条
                $list['data']  = $model->orderRaw('rand()')->select();
                $can_get_score = true;
                break;

            // 普通模式
            default:
                $list = $model->paginate($param['page_count'])->toArray();
                // 练习/看题得积分，第一页时才得积分
                $can_get_score = input('page/d') == 1;
                break;
        }
      
        if ($list['data']) {
            // 题目是否已收藏
            if ($param['user_id']) {
                $list['data'] = self::isCollected($param['user_id'], $list['data']);
            }

            if ($can_get_score) {
                $score_type    = input('type', '') == 'train' ? UserScoreType::TRAIN : UserScoreType::LOOK;
                $list['point'] = [
                    'get_point' => ScoreService::getScore($param['user_id'], $score_type),
                    'type'      => UserScoreType::getDescription($score_type)
                ];
            }

            // 合并材料题子题目
            $list['data'] = self::mergeMaterialQuestions($list['data']);
        }
        return $list;
    }


    /**
     * 获取试题列表
     * @param $params
     * @param [string]  试题ID
     * @param [int]     章节ID
     * @param [int]     用户ID
     * @param [int]     记录ID
     * @return array|int
     */
    public static function getQuestion($ids,$course_id=0,$user_id=0,$log_id=0)
    {
    
        $model = new static();
        $model->alias("c")->with(['materialQuestions.question'])
                ->where('is_material_child', 0)
                ->where('c.id','IN',$ids)
                ->order('c.id asc');
       
        if($course_id > 0){
   
            // if($log_id >0){

            //     // 根据章节ID回显
            //     $model->join('yalimedia_question_log_detail detail',"detail.question_id=c.id AND detail.course_id = {$course_id} AND user_id = {$user_id} AND detail.log_id = {$log_id}",'left')
            //             ->field('c.*,detail.content');
            // }else{
                // 最新记录回显
                $model->join('yalimedia_question_log_detail detail',"detail.question_id=c.id AND detail.course_id = {$course_id} AND user_id = {$user_id} AND detail.status=1",'left')
                        ->field('c.*,detail.content');
            // }
        }

        $param = [
            'cate_id'        => 0,                            // 按分类查询
            'kind'           => '',                           // 试题类型查询
            'status'         => CommonStatus::NORMAL,         // 状态查询
            'keyword'        => '',                           // 搜索关键词
            'user_id'        => 0,                            // 传入用户ID时，查询收藏状态
            'page_count'     => 9999,                           // 每页数量
            'sort'           => '',                           // 排序类型
            'just_get_count' => 0,                            // 仅获取题数
            'mode'           => 'normal',                     // normal=普通模式，memory=记忆模式，random=随机查询
            'memory_index'   => 0,                            // 记忆模式 - 上次做题题标
        ];
       
        // 能否获得积分标识
        $can_get_score = false;
        switch ($param['mode']) {
            // 记忆模式
            case 'memory':
                $list['data']  = $model->select();
                $can_get_score = true;
                break;

            // 随机模式
            case 'random':
                // 限制最多500条
                $list['data']  = $model->orderRaw('rand()')->select();
                $can_get_score = true;
                break;

            // 普通模式
            default:
                $list = $model->paginate($param['page_count'])->toArray();
        
                // 练习/看题得积分，第一页时才得积分
                $can_get_score = input('page/d') == 1;
                break;
        }

        if ($list['data']) {
            // 题目是否已收藏
            if ($param['user_id']) {
                $list['data'] = self::isCollected($param['user_id'], $list['data']);
            }

          
            
            if ($can_get_score) {
                $score_type    = input('type', '') == 'train' ? UserScoreType::TRAIN : UserScoreType::LOOK;
                $list['point'] = [
                    'get_point' => ScoreService::getScore($param['user_id'], $score_type),
                    'type'      => UserScoreType::getDescription($score_type)
                ];
            }

            $list['data'] = self::mergeMaterialQuestions($list['data'],$user_id,$log_id,$course_id);
        }
        
        return $list;
    }


    /**
     * 合并材料题子题目
     * @param $questions
     * @return mixed
     */
    public static function mergeMaterialQuestions($questions,$user_id=0,$log_id=0,$course_id=0)
    {
        
        $questions = collection($questions)->toArray();
      
        $sort      = 0;
        $material_questions = [];
        $content   = [];
        foreach ($questions as $key => $question) {

            if(!empty($question['content'])){
                $content = \json_decode($question['content'],true);

                $questions[$key]['content'] = $content;
            }
          
            // 单选、判断
            if($question['kind'] == 'JUDGE' || $question['kind'] == 'SINGLE'){

                //  答题回显
                if(isset($questions[$key]['content'])){
                    $new_data = array_column($question['options_json'],null,'key');


                    $new_data[$content['answer']]['click_index'] = true;
                    $questions[$key]['options_json'] = array_values($new_data);
                    $questions[$key]['answer_index'] = $content['answer'];
                    $questions[$key]['selectAnswer'] = $content['answer'];
                }
             
            }

            // 多选
            if($question['kind'] == 'MULTI'){
               
                if(isset($questions[$key]['content'])){
         
                    $new_data = array_column($question['options_json'],null,'key');
                  
                    $arr_data = explode(',',$content['answer']);
                  
                    foreach($arr_data as $va){
                        $new_data[$va]['click_index'] = true;
                    }
                    $questions[$key]['selectAnswer'] = $content['answer'];
                    $questions[$key]['options_json'] = array_values($new_data);
                }
            }

            // 填空题
            if($question['kind'] == 'FILL'){

                $fill  = explode('______',$question['title']);
                $title = [];
                foreach($fill as $k => $va){
                    
                    if(empty($va)){
                        continue;
                    }

                    if(isset($questions[$key]['content'])){
                        $width      = $content['answer'][$k]['width'] ?? '';
                        $value_text = $content['answer'][$k]['value'] ?? '';
                        
                        $title = array_merge($title,[['type' => 1, 'value' => $va,'width'=>''],['type' => 0, 'value' => $value_text,'width'=>$width]]);
                    }else{
                        $title = array_merge($title,[['type' => 1, 'value' => $va,'width'=>''],['type' => 0, 'value' => '','width'=>'']]);
                    }
                }
                $questions[$key]['fill_title'] = $title;
        
                unset($title);
            }
            
            // 问答题
            if($question['kind'] == 'SHORT'){
             
      
                if(isset($questions[$key]['content'])){
                    $questions[$key]['selectAnswer'] = $content['answer'];
                }
            }

            // 词汇题
            if($question['kind'] == 'WORD'){
   
                $xf_th_text = '';
                if(!empty($question['xf_content'])){
       
                    if($question['is_word'] == 0){
                        $xf_th_text .= '[word]';
                    }else{
                        $xf_th_text .= '[content]';
                    }

                    $xf_th_text .= $question['xf_content'];

                    if(!empty($question['vocabulary'])){
                        $xf_th_text .= '[vocabulary]'.$question['vocabulary'];
                    }

                    if(!empty($question['number_replace'])){
                        $xf_th_text .= '[number_replace]'.$question['number_replace'];
                    }
                }
                
                $questions[$key]['xf_text'] = $xf_th_text;
            }

            // 通话题
            if($question['kind'] == 'CALL'){
          
                // 模拟通话
                if(!empty($question['answer'])){
              
                    $answer = $question['answer'];
                    
                    $xf_answer = [];
                    foreach ($answer['config'] as $k => $v) {

                        $xf_th_text = '';
                        if(!empty($v['content'])){
                       
                            $xf_th_text .= '[content]'.$v['content'];
        
                            if(!empty($v['vocabulary'])){
                                $xf_th_text .= '[vocabulary]'.$v['vocabulary'];
                            }
        
                            if(!empty($v['number_replace'])){
                                $xf_th_text .= '[number_replace]'.$v['number_replace'];
                            }
                        }

                        $xf_answer['answer'][$k]['id']        = $v['id'];
                        $xf_answer['answer'][$k]['name']      = $v['name'];
                        $xf_answer['answer'][$k]['answer']    = $v['answer'];
                        $xf_answer['answer'][$k]['start_at']  = $v['start_at'];
                        $xf_answer['answer'][$k]['xf_text']   = $xf_th_text;

                        $xf_answer['user']   = $answer['user'];
                    }
                    $questions[$key]['answer'] = $xf_answer;
                }
            }

            // 材料题
            if ($question['kind'] == 'MATERIAL') {
       
                foreach ($question['material_questions'] as $kk=> $material_question) {

                    $new_question = $material_question['question'];
               
                    if($log_id > 0){
                        $new_content = DetailModel::where(['user_id' => $user_id,'question_id' => $material_question['question']['id'],'log_id' => $log_id,'course_id' => $course_id ])->value('content');
                    }else{
                        $new_content = DetailModel::where(['user_id' => $user_id,'question_id' => $material_question['question']['id'],'status' => 1,'course_id' => $course_id ])->value('content');
                    }
                   
                    if(isset($new_content)){
                        $new_content = json_decode($new_content,true);
                    }

                    $new_question['material_id']    = $question['id'];
                    $new_question['material_title'] = $question['title'];
                    $new_question['material_score'] = $question['score'] ?? 1;
                    $new_question['origin_answer']  = $material_question['question']['answer'];
                    $new_question['score']          = $material_question['score'];
                    $new_question['answer']         = $material_question['answer'];
                    $new_question['answer_index']   = '';
                    // with查询导致的数据格式问题，需要特殊处理
                    if (in_array($new_question['kind'], ['FILL', 'SHORT', 'CALL']) && $new_question['answer'] && is_string($new_question['answer'])) {
                        $new_question['answer'] = json_decode($new_question['answer'], true);
                    }


                    // 问答题
                    if($new_question['kind'] == 'SHORT'){
                        if(isset($new_content['answer'])){
                            $new_question['selectAnswer'] = $new_content['answer'];
                        }
                    }
                
                    // 填空题
                    if($new_question['kind'] == 'FILL'){
                        
                        $fill  = explode('______',$material_question['question']['title']);
                        $title = [];
                       
                        foreach($fill as $k =>$va){
                       
                            if(isset($new_content['answer'])){
                                
                                $width      = $new_content['answer'][$k]['width'] ?? '';
                                $value_text = $new_content['answer'][$k]['value'] ?? '';
                                $title = array_merge($title,[['type' => 1, 'value' => $va,'width'=>''],['type' => 0, 'value' => $value_text,'width'=>$width]]);
                                
                            }else{
                                $title = array_merge($title,[['type' => 1, 'value' => $va,'width'=>''],['type' => 0, 'value' => '','width'=>'']]);
                            }
                        }
                        $new_question['fill_title'] = $title;
                        $new_question['answer_index'] = empty($new_content['answer']) ? [[ 'value' => '']] : $new_content['answer'];
                        unset($title);
                    }

                    // 单选、判断
                    if($new_question['kind'] == 'JUDGE' || $new_question['kind'] == 'SINGLE'){
                        
                        //  答题回显
                        if(isset($new_content['answer'])){
                         
                            $new_question['options_json'] = json_decode($new_question['options_json'], true);

                            // 特殊格式处理
                            $keys = array_keys($new_question['options_json']);
                            if (isset($keys[0]) && $keys[0] && !is_numeric($keys[0])) {
                                $options_json = [];
                                foreach ($new_question['options_json'] as $option_key => $option_val) {
                                    $options_json[] = [
                                        'key'         => $option_key,
                                        'value'       => $option_val,
                                        'click_index' => false,
                                    ];
                                }
                                $new_question['options_json'] = $options_json;
                            }
                            $new_data = array_column($new_question['options_json'],null,'key');
                            $new_data[$new_content['answer']]['click_index']  = true;
                          
                            $new_question['options_json'] = array_values($new_data);
                            $new_question['answer_index'] = $new_content['answer'];
                        }
                    }


                    // 多选
                    if($new_question['kind'] == 'MULTI'){
                        if(isset($new_content['answer'])){
                            
                            $new_data = array_column($new_question['options_json'],null,'key');
                            $arr_data = explode(',',$new_content['answer']);
                            foreach($arr_data as $va){
                                $new_data[$va]['click_index'] = true;
                            }
                            $new_question['options_json'] = array_values($new_data);
                            $new_question['answer_index'] = $new_content['answer'];
                        }
                    }

                    if ($new_question['title_img'] && is_string($new_question['title_img'])) {
                        $new_question['title_img']  = cdnurl($new_question['title_img'], true);
                    }
                    if ($new_question['title_audio'] && is_string($new_question['title_audio'])) {
                        $new_question['title_audio']  = cdnurl($new_question['title_audio'], true);
                    }

                    if ($new_question['options_img'] && is_string($new_question['options_img'])) {
                        $new_question['options_img']  = json_decode($new_question['options_img'], true);
                    }
                    if ($new_question['options_json'] && is_string($new_question['options_json'])) {
                        $new_question['options_json'] = json_decode($new_question['options_json'], true);

                        // 特殊格式处理
                        $keys = array_keys($new_question['options_json']);
                        if (isset($keys[0]) && $keys[0] && !is_numeric($keys[0])) {
                            $options_json = [];
                            foreach ($new_question['options_json'] as $option_key => $option_val) {
                                $options_json[] = [
                                    'key'         => $option_key,
                                    'value'       => $option_val,
                                    'click_index' => false,
                                ];
                            }
                            $new_question['options_json'] = $options_json;
                        }
                    }
                    $new_question['show_full'] = false;

                    $sort++;
                    $new_question['sort'] = $sort;
                 
                    $material_questions[] = $new_question;
                }
           
                $questions[$key]['material_questions'] = $material_questions;
                
                

                unset($material_questions);
            }else{
                $sort++;
                $questions[$key]['sort'] = $sort;
                $questions[$key]['answer_index'] = $questions[$key]['answer_index'] ?? '';
                $questions[$key]['material_questions'] = [];
            }
        }
      
        return $questions;
    }



    /**
     * 获取试题列表
     * @param $params
     * @param [string]  试题ID
     * @param [int]     章节ID
     * @param [int]     用户ID
     * @param [int]     记录ID
     * @return array|int
     */
    public static function getQuestionDetail($ids,$course_id=0,$user_id=0,$log_id=0)
    {

        $model = new static();
        $model->alias("c")->with(['materialQuestions.question'])
                ->where('is_material_child', 0)
                ->where('c.id','IN',$ids)
                ->order('c.id DESC');
        
        $model->join('yalimedia_question_log_detail detail',"detail.question_id=c.id AND detail.course_id = {$course_id} AND user_id = {$user_id} AND detail.log_id = {$log_id}",'left')
        ->field('c.*,detail.content');

        $param = [
            'cate_id'        => 0,                            // 按分类查询
            'kind'           => '',                           // 试题类型查询
            'status'         => CommonStatus::NORMAL,         // 状态查询
            'keyword'        => '',                           // 搜索关键词
            'user_id'        => 0,                            // 传入用户ID时，查询收藏状态
            'page_count'     => 20,                           // 每页数量
            'sort'           => '',                           // 排序类型
            'just_get_count' => 0,                            // 仅获取题数
            'mode'           => 'normal',                     // normal=普通模式，memory=记忆模式，random=随机查询
            'memory_index'   => 0,                            // 记忆模式 - 上次做题题标
        ];
      
        $list = $model->paginate($param['page_count'])->toArray();
        // 练习/看题得积分，第一页时才得积分
        $can_get_score = input('page/d') == 1;

        if ($list['data']) {

            // 题目是否已收藏
            if ($param['user_id']) {
                $list['data'] = self::isCollected($param['user_id'], $list['data']);
            }

            if ($can_get_score) {
                $score_type    = input('type', '') == 'train' ? UserScoreType::TRAIN : UserScoreType::LOOK;
                $list['point'] = [
                    'get_point' => ScoreService::getScore($param['user_id'], $score_type),
                    'type'      => UserScoreType::getDescription($score_type)
                ];
            }

            $list['data'] = self::mergeMaterialQuestionsDetail($list['data'],$user_id,$log_id);
        }
        return $list;
    }


    /**
     * 合并材料题子题目
     * @param $questions
     * @return mixed
     */
    public static function mergeMaterialQuestionsDetail($questions,$user_id=0,$log_id=0)
    {
      
        $questions = collection($questions)->toArray();
        $sort      = 0;
        $material_questions = [];
        foreach ($questions as $key => $question) {
      
            if(!empty($question['content'])){
                $content = \json_decode($question['content'],true);
                $questions[$key]['content'] = $content;
            }else{
                $content = [];
            }

            // 单选、判断
            if($question['kind'] == 'JUDGE' || $question['kind'] == 'SINGLE'){
                $new_data = array_column($question['options_json'],null,'key');
                //  答题回显
                $new_data[$question['answer']]['right_index']  = true;
                if(isset($content['answer'])){
                    $new_data[$content['answer']]['click_index']  = true;
                    $questions[$key]['answer_index'] = $content['answer'];
                }
                $questions[$key]['options_json'] = array_values($new_data);
            }

            // 多选
            if($question['kind'] == 'MULTI'){
                $new_data = array_column($question['options_json'],null,'key');
                $arr_data2 = explode(',',$question['answer']);
                foreach($arr_data2 as $va){
                    $new_data[$va]['right_index'] = true;
                }
                if(isset($content['answer'])){
                    $arr_data  = explode(',',$content['answer']);
                    foreach($arr_data as $va){
                        $new_data[$va]['click_index'] = true;
                    }
                }
                $questions[$key]['options_json'] = array_values($new_data);
            }

            // 填空题
            if($question['kind'] == 'FILL'){

                $fill  = explode('______',$question['title']);
                
                $title = [];
                foreach($fill as $k => $va){
                    
                    if(empty($va)){
                        continue;
                    }

                    $right_text = '';
                    if(isset($question['answer'][$k]['answers'])){
                        $right_text  = current($question['answer'][$k]['answers']);
                    }
                    $right_index = false;
                    if(isset($content['answer'])){
                        $width      = $content['answer'][$k]['width'] ?? '';
                        $value_text = $content['answer'][$k]['value'] ?? '';

                        $right_index     = false;
                        if($value_text == $right_text){
                            $right_index = true;
                        }
                        $title = array_merge($title,[['type' => 1, 'value' => $va,'width'=>'','right_index'=>$right_index],['type' => 0, 'value' => $value_text,'width'=>$width,'right_index'=>$right_index],['type' => 2, 'value' => $right_text,'width'=>'','right_index'=>$right_index]]);
                    }else{
                        $title = array_merge($title,[['type' => 1, 'value' => $va,'width'=>'','right_index'=>$right_index],['type' => 0, 'value' => '','width'=>'','right_index'=>$right_index],['type' => 2, 'value' => $right_text,'width'=>'','right_index'=>$right_index]]);
                    }
                }
                
                $questions[$key]['fill_title'] = $title;
                unset($title);
            }
         
            // 问答题
            if($question['kind'] == 'SHORT'){
            
                if(isset($content['answer'])){
                    $questions[$key]['selectAnswer'] = $content['answer'];
                }
            }


            // 词汇题
            if($question['kind'] == 'WORD'){

                $xf_th_text = '';
                if(!empty($question['xf_content'])){
                    
                    if($question['is_word'] == 0){
                        $xf_th_text .= '[word]';
                    }else{
                        $xf_th_text .= '[content]';
                    }

                    $xf_th_text .= $question['xf_content'];

                    if(!empty($question['vocabulary'])){
                        $xf_th_text .= '[vocabulary]'.$question['vocabulary'];
                    }

                    if(!empty($question['number_replace'])){
                        $xf_th_text .= '[number_replace]'.$question['number_replace'];
                    }
                }
                
                $questions[$key]['xf_text'] = $xf_th_text;
            }
            

            // 通话题
            if($question['kind'] == 'CALL'){
     
                // 模拟通话
                if(!empty($question['answer'])){
                    
                    $answer = $question['answer'];
                    
                    $xf_answer = [];
                    foreach ($answer['config'] as $k => $v) {

                        $xf_th_text = '';
                        if(!empty($v['content'])){
                       
                            $xf_th_text .= '[content]'.$v['content'];
        
                            if(!empty($v['vocabulary'])){
                                $xf_th_text .= '[vocabulary]'.$v['vocabulary'];
                            }
        
                            if(!empty($v['number_replace'])){
                                $xf_th_text .= '[number_replace]'.$v['number_replace'];
                            }
                        }

                        $xf_answer['answer'][$k]['id']        = $v['id'];
                        $xf_answer['answer'][$k]['name']      = $v['name'];
                        $xf_answer['answer'][$k]['answer']    = $v['answer'];
                        $xf_answer['answer'][$k]['start_at']  = $v['start_at'];
                        $xf_answer['answer'][$k]['xf_text']   = $xf_th_text;

                        $xf_answer['user']   = $answer['user'];
                    }
                    $questions[$key]['answer'] = $xf_answer;
                }
            }

            // 材料题
            if ($question['kind'] == 'MATERIAL') {
       
                foreach ($question['material_questions'] as $kk=> $material_question) {

                    $new_question = $material_question['question'];
          
                    if($log_id > 0){
                        $new_content = DetailModel::where(['user_id' => $user_id,'question_id' => $material_question['question']['id'],'log_id' => $log_id ])->value('content');
                    }else{
                        $new_content = DetailModel::where(['user_id' => $user_id,'question_id' => $material_question['question']['id'],'status' => 1 ])->value('content');
                    }
                  
                    if(isset($new_content)){
                        $new_content = json_decode($new_content,true);
                    }

                    $new_question['material_id']    = $question['id'];
                    $new_question['material_title'] = $question['title'];
                    $new_question['material_score'] = $question['score'] ?? 1;
                    $new_question['origin_answer']  = $material_question['question']['answer'];
                    $new_question['score']          = $material_question['score'];
                    $new_question['answer']         = $material_question['answer'];
                    $new_question['answer_index']   = '';
                    // with查询导致的数据格式问题，需要特殊处理
                    if (in_array($new_question['kind'], ['FILL', 'SHORT', 'CALL']) && $new_question['answer'] && is_string($new_question['answer'])) {
                 
                        $new_question['answer'] = json_decode($new_question['answer'], true);
                    }


                    // 问答题
                    if($new_question['kind'] == 'SHORT'){
                        if(isset($new_content['answer'])){
                            $new_question['selectAnswer'] = $new_content['answer'];
                        }
                    }
                
                    
                    if($new_question['kind'] == 'FILL'){
                        $fill  = explode('______',$material_question['question']['title']);
                        $title = [];
             
                        foreach($fill as $k =>$va){
                            
                            $right_text   = '';
                            $right_index  = false;
                            if(isset($new_question['answer'][$k]['answers'])){
                                $right_text  = current($new_question['answer'][$k]['answers']);
                            }
                            
                            if(isset($new_content['answer'])){
                              
                                $width      = $new_content['answer'][$k]['width'] ?? '';
                                $value_text = $new_content['answer'][$k]['value'] ?? '';

                                $right_index     = false;
                                if($value_text == $right_text){
                                    $right_index = true;
                                }
                                if(isset($new_content['answer'][$k]) && !empty($new_content['answer'][$k])){
                                    $new_content['answer'][$k]['right_index'] = $right_index;
                                }
                                
                                $title = array_merge($title,[['type' => 1, 'value' => $va,'width'=>'','right_index'=>$right_index],['type' => 0, 'value' => $value_text,'width'=>$width,'right_index'=>$right_index],['type' => 2, 'value' => $right_text,'width'=>'','right_index'=>$right_index]]);
                                
                            }else{
                                $title = array_merge($title,[['type' => 1, 'value' => $va,'width'=>'','right_index'=>$right_index],['type' => 0, 'value' => '','width'=>'','right_index'=>$right_index],['type' => 2, 'value' => $right_text,'width'=>'','right_index'=>$right_index]]);
                            }
                        }

                        if(isset($new_content['answer']) && count($new_content['answer']) == 1){
                            $new_question['right_index']  = $right_index;
                        }
                        $new_question['fill_title']   = $title;
                        $new_question['answer_index'] = empty($new_content['answer']) ? [[ 'value' => '']] : $new_content['answer'];
                        unset($title);
                    }

                    // 单选、判断
                    if($new_question['kind'] == 'JUDGE' || $new_question['kind'] == 'SINGLE'){
                  

                        //  答题回显
                        if(isset($new_content['answer'])){

                            $new_question['options_json'] = json_decode($new_question['options_json'], true);

                            // 特殊格式处理
                            $keys = array_keys($new_question['options_json']);
                            if (isset($keys[0]) && $keys[0] && !is_numeric($keys[0])) {
                                $options_json = [];
                                foreach ($new_question['options_json'] as $option_key => $option_val) {
                                    $options_json[] = [
                                        'key'         => $option_key,
                                        'value'       => $option_val,
                                        'click_index' => false,
                                        'right_index' => false,
                                    ];
                                }
                                $new_question['options_json'] = $options_json;
                            }

                            $new_data = array_column($new_question['options_json'],null,'key');
                            $new_data[$new_question['answer']]['click_index']  = true;
                            $right_index = true;
                            if($new_question['answer'] != $new_content['answer']){
                                $new_data[$new_content['answer']]['click_index']  = true;
                                $right_index = false;
                            }

                            $new_data[$new_question['answer']]['right_index']  = true;
                            $new_question['options_json'] = array_values($new_data);
                            $new_question['answer_index'] = $new_content['answer'];

                            // 匹配选择题
                            if($question['m_type'] == 5){
                                $new_question['right_index']  = $right_index;
                            }
                        }
                    }


                    // 多选
                    if($new_question['kind'] == 'MULTI'){

                        if(isset($new_content['answer'])){
                            
                            $new_data = array_column($new_question['options_json'],null,'key');
                            $arr_data = explode(',',$new_content['answer']);
                            foreach($arr_data as $va){
                                $new_data[$va]['click_index'] = true;
                            }

                            $arr_data2 = explode(',',$new_question['answer']);
                            foreach($arr_data2 as $va){
                                $new_data[$va]['click_index'] = true;
                                $new_data[$va]['right_index'] = true;
                            }

                            $new_question['options_json'] = array_values($new_data);
                            $new_question['answer_index'] = $new_content['answer'];
                        }
                    }

                    if ($new_question['title_img'] && is_string($new_question['title_img'])) {
                        $new_question['title_img']  = cdnurl($new_question['title_img'], true);
                    }
                    if ($new_question['title_audio'] && is_string($new_question['title_audio'])) {
                        $new_question['title_audio']  = cdnurl($new_question['title_audio'], true);
                    }

                    if ($new_question['options_img'] && is_string($new_question['options_img'])) {
                        $new_question['options_img']  = json_decode($new_question['options_img'], true);
                    }
                    if ($new_question['options_json'] && is_string($new_question['options_json'])) {
                        $new_question['options_json'] = json_decode($new_question['options_json'], true);

                        // 特殊格式处理
                        $keys = array_keys($new_question['options_json']);
                        if (isset($keys[0]) && $keys[0] && !is_numeric($keys[0])) {
                            $options_json = [];
                            foreach ($new_question['options_json'] as $option_key => $option_val) {
                                $options_json[] = [
                                    'key'         => $option_key,
                                    'value'       => $option_val,
                                    'click_index' => false,
                                ];
                            }
                            $new_question['options_json'] = $options_json;
                        }
                    }
                    $new_question['show_full'] = false;

                    $sort++;
                    $new_question['sort'] = $sort;
                 
                    $material_questions[] = $new_question;
                }
           
                $questions[$key]['material_questions'] = $material_questions;
                
                unset($material_questions);
            }else{
                $sort++;
                $questions[$key]['sort'] = $sort;
                $questions[$key]['answer_index'] = $questions[$key]['answer_index'] ?? '';
                $questions[$key]['material_questions'] = [];
            }
        }
    
        return $questions;
    }

    
    
}
